package com.example.administrator.printoutindemo;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;


import com.example.administrator.printoutindemo.services.Tools;
import com.example.administrator.printoutindemo.services.dyjApplication;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.util.ArrayList;
import java.util.List;


public class StoreListAlarmOp extends Activity {
	private ListView store_alarm_listView;
	private Button store_alram_closeAll;

	private StoreDoorAlarm sdala;
	private List<StoreDoorAlarm> li;

	private StoreListAlarmOpAdapter adapter;

	ProgressDialog progressDiaog;

	private static final String WEBSERVICE_CONFIG = "webServiceInfo";

	private static final int LOGINSUCCESS = 0;
	private static final int NETWORKERROR = 2;
	private static final int SYSERROR = 3;
	private static final int UPSUCCESS = 4;
	private static final int UPEROOR = 5;

	private final Handler hanlder = new Handler() {
		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
				case LOGINSUCCESS:

					bindList();

					progressDiaog.dismiss();
					break;
				case UPSUCCESS:
					bindList();
					Toast.makeText(StoreListAlarmOp.this, "操作成功!",
							Toast.LENGTH_LONG).show();
					progressDiaog.dismiss();
					break;
				case UPEROOR:
					bindList();

					Toast.makeText(StoreListAlarmOp.this, "操作失败!",
							Toast.LENGTH_LONG).show();
					progressDiaog.dismiss();
					break;
				case NETWORKERROR:

					Toast.makeText(StoreListAlarmOp.this, "网络或系统异常!",
							Toast.LENGTH_LONG).show();
					progressDiaog.dismiss();
					break;
				case SYSERROR:

					Toast.makeText(StoreListAlarmOp.this, "系统异常!",
							Toast.LENGTH_LONG).show();
					progressDiaog.dismiss();
					break;

				default:
					progressDiaog.dismiss();
					break;
			}

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.store_activity_listalarm);

		store_alarm_listView = (ListView) findViewById(R.id.store_alarm_listView);
		store_alram_closeAll = (Button) findViewById(R.id.store_alram_closeAll);

		adapter = new StoreListAlarmOpAdapter(this, hanlder);
		sdala = new StoreDoorAlarm();

		final int user_id = ((dyjApplication) getApplication()).get_user_id();

		store_alram_closeAll
				.setOnClickListener(new store_alram_closeAll_click());

		if (user_id != 0) {

			progressDiaog = new ProgressDialog(StoreListAlarmOp.this);
			progressDiaog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置为圆形进度条
			progressDiaog.setTitle("提示");
			// progressDiaog.setIcon(R.drawable.ic_launcher);//设置进度条的图标
			progressDiaog.setMessage("系统正在努力与服务器联系，请稍后......");
			progressDiaog.setIndeterminate(false);// 设置进度条不明确
			progressDiaog.setCancelable(true);

			progressDiaog.show();
			new Thread(new Runnable() {

				@Override
				public void run() {

					try {
						li = callWebServiceGetInfo(String.valueOf(user_id));

						if (li != null) {
							Message m = new Message();
							m.what = StoreListAlarmOp.LOGINSUCCESS;
							hanlder.sendMessage(m);
						}

					} catch (Exception e) {
						Message m = new Message();
						m.what = StoreListAlarmOp.SYSERROR;
						hanlder.sendMessage(m);
					}

				}
			}).start();
		} else {
			Tools.showDialogInfo(this, "登录已过期，请重新登录");
		}
	}

	private class store_alram_closeAll_click implements View.OnClickListener {

		@Override
		public void onClick(View v) {

			new Thread(new Runnable() {

				@Override
				public void run() {
					boolean bl = false;

					for (int i = 0; i < li.size(); i++) {

						bl = uploadInfo(li.get(i));
					}

					if (bl) {
						Message m = new Message();
						m.what = StoreListAlarmOp.UPSUCCESS;
						hanlder.sendMessage(m);

					} else {
						Message m = new Message();
						m.what = StoreListAlarmOp.UPEROOR;
						hanlder.sendMessage(m);
					}

				}
			}).start();

		}
	}

	private void bindList() {

		adapter.setList(li);
		store_alarm_listView.setAdapter(adapter);
	}

	// 上传数据至服务器
	private boolean uploadInfo(StoreDoorAlarm s) {

		boolean bl = false;

		try {

			/****************** 调用webService ***********************/
			// 调用.net 的WebService.
			String nameSpace = "http://dyjapp.org/";
			String methodName = "addCommand";

			SharedPreferences sPreferencces = getSharedPreferences(
					WEBSERVICE_CONFIG, 0);

			String url = "http://" + sPreferencces.getString("ip", "") + ":"
					+ sPreferencces.getString("Port", "")
					+ "/StoreService.asmx";// "http://192.168.1.101/webservice/default.asmx";
			// // 10.0.2.2
			// 为Android模拟器的本地(localhost)IP
			String soapAction = nameSpace + methodName;

			// 设置连接参数
			SoapObject request = new SoapObject(nameSpace, methodName);

			// 增加属性参数。 将相关的函数参数放入到过程中。
			request.addProperty("type", "alarm");
			request.addProperty("paradd", s.getParadd());

			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
			// V1.1）;

			// 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
			// 不指定rpc方式则用true否则要用false
			envelope.dotNet = true;

			// envelope.setOutputSoapObject(request);//设置请求参数
			envelope.bodyOut = request; // enveloper.bodyOut=request 与
			// envelope.setOutputSoapObject(request)
			// 效果相同。
			// step4 创建HttpTransportSE对象
			HttpTransportSE ht = new HttpTransportSE(url);
			// step5 调用WebService
			ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
			if (envelope.getResponse() != null) {
				SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
				if ("ok".equals(response.toString())) {
					bl = true;
				}

			}
			/****************** 调用webService结束 ***********************/

		} catch (Exception e) {
			e.printStackTrace();
		}

		return bl;
	}

	private List<StoreDoorAlarm> callWebServiceGetInfo(String user_id) {

		List<StoreDoorAlarm> result = null;

		try {

			/****************** 调用webService ***********************/
			// 调用.net 的WebService.
			String nameSpace = "http://dyjapp.org/";
			String methodName = "getAlarmlist";
			SharedPreferences sPreferencces = getSharedPreferences(
					WEBSERVICE_CONFIG, 0);

			String url = "http://" + sPreferencces.getString("ip", "") + ":"
					+ sPreferencces.getString("Port", "")
					+ "/StoreService.asmx";

			String soapAction = nameSpace + methodName;

			// 设置连接参数
			SoapObject request = new SoapObject(nameSpace, methodName);

			// 增加属性参数。 将相关的函数参数放入到过程中。
			// request.addProperty("user_id", user_id);

			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
			// V1.1）;

			// 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
			// 不指定rpc方式则用true否则要用false
			envelope.dotNet = true;

			// envelope.setOutputSoapObject(request);//设置请求参数
			envelope.bodyOut = request; // enveloper.bodyOut=request 与
			// envelope.setOutputSoapObject(request)
			// 效果相同。
			// step4 创建HttpTransportSE对象
			HttpTransportSE ht = new HttpTransportSE(url);
			// step5 调用WebService
			ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
			if (envelope.getResponse() != null) {
				SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
				// if ("1".equals(response.toString())) {
				String t = response.toString();

				if (!t.equals("")) {

					result = new ArrayList<StoreDoorAlarm>();
					StoreDoorAlarm sda = null;
					String[] ts = t.split("@");

					if (ts.length > 0) {

						for (int i = 0; i < ts.length; i++) {
							sda = new StoreDoorAlarm();
							String[] tss = ts[i].split(":");
							sda.setParadd(tss[0]);
							sda.setBh(tss[1]);
							sda.setType(1);

							result.add(sda);
						}
					}

				}

			}
			/****************** 调用webService结束 ***********************/

		} catch (Exception e) {
			// TODO: handle exception
			progressDiaog.dismiss();
		}

		return result;
	}
}